//
//  Util.m
//  QBIM
//
//  Created by liunian on 14-3-17.
//  Copyright (c) 2014年 liunian. All rights reserved.
//

#import "Util.h"

@implementation Util

#pragma mark - JSON
+ (NSDictionary *)convertJSONToDict:(NSString *)string
{
    NSError *error = nil;
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    if (!data || data == nil) {
        return nil;
    }
    NSDictionary *respDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    if (nil == error){
        return respDict;
    }else{
        return nil;
    }
}

+ (NSString *)convertObjectToJSON:(id)object;
{
    NSError *error = nil;
    NSData  *data = nil;
    if (object) {
        data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
    }
    
    if (data == nil) {
        return nil;
    }
    
    return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
#pragma mark - Dictionary

+ (id)getElementForKey:(id)key fromDict:(NSDictionary *)dict
{
    if(![dict isKindOfClass:[NSDictionary class]])
        return nil;
    
    id obj = [dict objectForKey:key];
    if ([obj isKindOfClass:[NSString class]] && [obj isEqual:@""]) {
        return nil; //空字符串
    } else if ([obj isKindOfClass:[NSNull class]]) {
        return nil; //空类
    }
    return obj;
}

+ (id)getElementForKey:(id)key fromDict:(NSDictionary *)dict forClass:(Class)forClass
{
    if(![dict isKindOfClass:[NSDictionary class]])
        return nil;
    
    id obj = [dict objectForKey:key];
    if ([obj isKindOfClass:forClass]) {
        if ([obj isKindOfClass:[NSString class]] && [obj isEqual:@""]) {
            return nil;
        } else {
            return obj;
        }
    }
    return nil;
}

+ (id)getElementForKey:(id)key fromDict:(NSDictionary *)dict character:(NSCharacterSet*)character
{
    if(![dict isKindOfClass:[NSDictionary class]])
        return nil;
    
    id obj = [dict objectForKey:key];
    if ([obj isKindOfClass:[NSString class]])
    {
        if (!obj || [obj isEqual:@""])
        {
            return nil;
        }
        else
        {
            if(character)
            {
                return [obj stringByTrimmingCharactersInSet:character];
            }
            return obj;
        }
    }
    else if ([obj isKindOfClass:[NSNull class]])
    {
        return nil; //空类
    }
    return obj;
}


@end
